package com.handsome.原型模式.浅拷贝深拷贝;


import java.io.*;
import java.util.Date;

/**
 * 通过序列化实现深拷贝
 *
 * @author niechun
 * @date 2023/1/17 21:05
 */
public class DeepSheep2 implements Cloneable, Serializable {
    private String name;

    private int age;

    private Date date;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    protected DeepSheep2 clone() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        DeepSheep2 deepSheep2=null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);

            deepSheep2= (DeepSheep2)ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            //关闭流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


        return  deepSheep2;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
